package com.easystore.orm
{
import com.easystore.orm.metadata.MetadataManager;
import com.easystore.orm.utilities.CheckUtil;

import flash.events.Event;
import flash.events.EventDispatcher;
import flash.events.IOErrorEvent;
import flash.net.URLLoader;
import flash.net.URLRequest;
import flash.utils.Dictionary;
import flash.utils.getDefinitionByName;

import mx.controls.Alert;
	
public class EasyStoreProperties extends EventDispatcher
{
	public static const MAX_POOL_SIZE : String = "easystore.connection.max_pool_size";
	public static const USE_ENCRYPTED_DATA : String = "easystore.use_encryption";
	public static const AUTO_CREATE_DB : String = "easystore.connection.auto_create_file";
	public static const DB_FILE_DIRECTORY : String = "easystore.connection.database.directory";
	public static const DB_FILE_NAME : String = "easystore.connection.database.name";
	public static const PROPERTIES_LOADED : String = "PROPERTIES_LOADED";

	private static var __instance : EasyStoreProperties;
	private var __properties : Dictionary;
	
	public function EasyStoreProperties(internalClass : Internal) 
	{
		CheckUtil.checkNotNull(internalClass,"internalClass", "EasyStoreProperties.<constructor>" );
	}
	
	public static function getInstance() : EasyStoreProperties 
	{
		if (__instance == null ) {
			__instance = new EasyStoreProperties(new Internal());
		}
		return __instance;
	}
	
	public function getProperty(aKey : String) : * 
	{
		return __properties[aKey];	
	}

	public function setProperty(aKey : String, aValue : *) : * 
	{
		__properties[aKey] = aValue;
		return aValue;
	}
	
	public function loadProperties(propertiesURL : String) : void 
	{
		var urlRequest : URLRequest = new URLRequest(propertiesURL);
		var loader : URLLoader = new URLLoader(urlRequest);
		loader.addEventListener(Event.COMPLETE , parseXML );
		loader.addEventListener(IOErrorEvent.IO_ERROR , failToLoadXML );
		loader.load(urlRequest);
	}
	
	private function parseXML(event : Event) : void 
	{
		var xml : XML = XML( URLLoader(event.target).data );
		var connectionProperties :XMLList = xml.properties;
		var mappings : XMLList = xml.mappings;
		__properties = new Dictionary();
		
		for each(var item : XML in connectionProperties.children() ) {
			setProperty( item.@name.toString()  , item.@value.toString() );
		}
		
		for each(var item2 : XML  in mappings.children() ) {
			MetadataManager.getInstance().loadMetadata( getDefinitionByName(item2.@entity.toString()) ) ;
		}
		
		dispatchEvent( new Event (PROPERTIES_LOADED) );
	}
	
	private function failToLoadXML( event : IOErrorEvent) : void 
	{
		Alert.show("fail to load properties");
	}
}
}
class Internal {}